//
//  SAStatisticsCommissionVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/23.
//

#import "SAStatisticsCommissionVC.h"
#import "SASystemEmpCommissionAPI.h"
#import "SAStatisticsCommissionCell.h"
#import "SAStatisticsCommissionModel.h"
#import "SADatePickerView.h"
#import "SASearchStoreUserView.h"
#import "SAStoreUserModel.h"

#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"
#import "BubbleTableView.h"

@interface SAStatisticsCommissionVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSString *memberName;
@property (nonatomic, strong) NSString *memberId;
@property (nonatomic, strong) UILabel *countLab;
@property (nonatomic, strong) UILabel *startDateLab;
@property (nonatomic, strong) UIButton *stateBtn;
@property (nonatomic, strong) SASystemEmpCommissionAPI *systemEmpCommissionAPI;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSMutableArray<SAStatisticsCommissionModel *> *dataMarr;
@property (nonatomic, strong) SAStoreUserModel *userModel;

@property (nonatomic, strong) UILabel *allShopLab;
@property (nonatomic, strong) UIImageView *allowImageV2;
@property (nonatomic, strong) NSString *selectDate;

@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreModel *> *storeList;
@property (nonatomic, strong) BubbleTableView *storeBubbleView;
@property (nonatomic, assign) NSInteger storeRow;

@end

@implementation SAStatisticsCommissionVC

- (void)viewDidLoad {
    [super viewDidLoad];

}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.systemEmpCommissionAPI == api) {
        if (self.currentPage == 1) {
            [self.dataMarr removeAllObjects];
            self.countLab.text = @"";
        }
        NSMutableArray<SAStatisticsCommissionModel *> *marr = [SAStatisticsCommissionModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        for (SAStatisticsCommissionModel *model in marr) {
            [self.dataMarr addObject:model];
        }
        self.tipView.hidden = self.dataMarr.count > 0;
        self.countLab.hidden = self.dataMarr.count == 0;
        [self.tableView reloadData];
    }else if (self.systemStoreStoreListAPI == api) {
        self.storeList = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        for (NSInteger i = 0; i < self.storeList.count; i++) {
            if ([SAValueManger shareInStance].userInfo.merchantId == self.storeList[i].merchantId) {
                self.storeRow = i;
            }
        }
        [self showStoreList];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAStatisticsCommissionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAStatisticsCommissionCell" forIndexPath:indexPath];
    SAStatisticsCommissionModel *model = self.dataMarr[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(80.5);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(void)clickedSearchBtn {
    NSString *empName = @"";
    if (self.userModel != nil) {
        empName = self.userModel.empName;
    }
    SASearchStoreUserView *searchStoreUserView = [[SASearchStoreUserView alloc] initWithEmpName:empName];

    UIViewController *vc = nil;
    [searchStoreUserView showView:vc];
    WeakSelf
    searchStoreUserView.selectBlock = ^(SAStoreUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        if (userModel == nil) {
            weakSelf.systemEmpCommissionAPI.empName = @"";
        }else {
            weakSelf.systemEmpCommissionAPI.empName = userModel.empName;
        }
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    };
}

-(void)clickedStateBtn {
    WeakSelf
    SADatePickerView *pickerView = [[SADatePickerView alloc] initWithSlectedDate:self.selectDate];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:@"9999-12-31"];
        if ([date1 compare:date2] == NSOrderedDescending) {
            [Prompt popPromptViewWithMsg:@"开始日期不能大于截止日期" duration:2];
        }else {
            weakSelf.selectDate = selectedDate;
            [weakSelf formatterDate:selectedDate];
            weakSelf.currentPage = 1;
            weakSelf.systemEmpCommissionAPI.date = selectedDate;
            [weakSelf loadData];
        }
    };
}

-(void)loadData {
    self.systemEmpCommissionAPI.currentPage = self.currentPage;
    [self.systemEmpCommissionAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - event
-(void)clickedAllowBtn2 {
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *crossStoreSummary = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"crossStoreSummary"]];
    if ([crossStoreSummary isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有跨店查统计权限,请联系店长添加" duration:2];
        return;
    }
    
    if (self.storeList.count > 0) {
        [self showStoreList];
    }else {
        self.systemStoreStoreListAPI.returnAll = @"true";
        [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}
    
-(void)showStoreList{
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreModel *model in self.storeList) {
        if (model.storeName.length == 0) {
            model.storeName = @"";
        }
        [marr addObject:model.storeName];
    }
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.storeBubbleView) {
        self.storeBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.storeRow = row;
            self.systemEmpCommissionAPI.merchantId = @(self.storeList[row].merchantId).stringValue;
            self.allShopLab.text = rowString;
            self.currentPage = 1;
            [self loadData];
        } hideBlock:^{
            self.storeBubbleView = nil;
        }];
        [self.storeBubbleView showWithTargetView:self.allowImageV2 maskSuperView:window];
        [self.storeBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.storeBubbleView.bubbleCellHeight = 50;
        self.storeBubbleView.selectRow = self.storeRow;
        self.storeBubbleView.isBubbleScrollEnabled = YES;
        self.storeBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}


-(void)formatterDate:(NSString *)date {
    NSArray *arr = [date componentsSeparatedByString:@"-"];
    if (arr.count == 3) {
        self.startDateLab.text = [NSString stringWithFormat:@"%zd年%zd月",[arr[0] integerValue],[arr[1] integerValue]];
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"员工提成"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    self.currentPage = 1;
    self.memberName = @"";
    self.memberId = @"";
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [searchBtn setImage:[UIImage imageNamed:@"Sale_screen"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(clickedSearchBtn) forControlEvents:UIControlEventTouchUpInside];
//    [self addRightViews:@[searchBtn]];
    
    UIView *grayView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 36)];
    grayView.backgroundColor = kBgColor;
    [self.view addSubview:grayView];
    
    UILabel *allShopLab = [[UILabel alloc] init];
    allShopLab.text = [SAValueManger shareInStance].userInfo.storeName;
    allShopLab.font = kBFont(15);
    allShopLab.textColor = kBlackColor;
    [grayView addSubview:allShopLab];
    self.allShopLab = allShopLab;
    
    UIImageView *allowImageV2 = [[UIImageView alloc] init];
    allowImageV2.image = [UIImage imageNamed:@"bule_downAllow"];
    [grayView addSubview:allowImageV2];
    allowImageV2.contentMode = UIViewContentModeCenter;
    self.allowImageV2 = allowImageV2;
    
    UIButton *allowBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [allowBtn2 addTarget:self action:@selector(clickedAllowBtn2) forControlEvents:UIControlEventTouchUpInside];
    [grayView addSubview:allowBtn2];
    
    [allShopLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(28));
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_lessThanOrEqualTo(kScaleNum(150));
        make.width.mas_greaterThanOrEqualTo(kScaleNum(50));
    }];
    
    [allowImageV2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_equalTo(kScaleNum(55));
        make.left.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(-10));
    }];
    
    [allowBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.right.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(30));
    }];
    
    UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 35, kBaseScreenWidth, 1)];
    line.backgroundColor = kColor(230, 230, 230, 1);
    [grayView addSubview:line];
    
    [self.view addSubview:self.countLab];
    [self.view addSubview:self.startDateLab];
    [self.view  addSubview:self.stateBtn];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    self.selectDate = timeFormatStr;
    [self formatterDate:timeFormatStr];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.tipView];
    
    self.currentPage = 1;
    self.systemEmpCommissionAPI.pageSize = 20;
    self.systemEmpCommissionAPI.date = timeFormatStr;
    self.systemEmpCommissionAPI.merchantId = @([SAValueManger shareInStance].userInfo.merchantId).stringValue;
    [self loadData];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
}

-(UILabel *)countLab {
    if (!_countLab) {
        _countLab = [[UILabel alloc] initWithFrame:SARectMake(120, StatusHeight + 36, 245, 35)];
        _countLab.font = kFont(15);
        _countLab.adjustsFontSizeToFitWidth = YES;
        _countLab.minimumScaleFactor = 0.8;
        _countLab.textColor = kLightgGrayColor;
        _countLab.textAlignment = NSTextAlignmentRight;
    }
    return _countLab;
}

- (UILabel *)startDateLab {
    if (!_startDateLab) {
        _startDateLab = [[UILabel alloc] initWithFrame:SARectMake(28, StatusHeight + 36, 90, 35)];
        _startDateLab.textColor = kLightgGrayColor;
        _startDateLab.font = kFont(15);
        _startDateLab.textAlignment = NSTextAlignmentLeft;
    }
    return _startDateLab;
}

-(UIButton *)stateBtn {
    if (!_stateBtn) {
        _stateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_stateBtn setImage:[UIImage imageNamed:@"down_arrow2"] forState:UIControlStateNormal];
        _stateBtn.frame = SARectMake(20, StatusHeight + 36, 200, 35);
        _stateBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [_stateBtn addTarget:self action:@selector(clickedStateBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _stateBtn;
}

-(SASystemEmpCommissionAPI *)systemEmpCommissionAPI {
    if (!_systemEmpCommissionAPI) {
        _systemEmpCommissionAPI = [SASystemEmpCommissionAPI apiWithDelegate:self];
    }
    return _systemEmpCommissionAPI;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 71), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 71)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAStatisticsCommissionCell class] forCellReuseIdentifier:@"SAStatisticsCommissionCell"];
    }
    return _tableView;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 71), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 71))];
        _tipView.backgroundColor = [UIColor whiteColor];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 106, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

-(NSMutableArray<SAStatisticsCommissionModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

-(NSMutableArray<SAStoreModel *> *)storeList {
    if (!_storeList) {
        _storeList = [NSMutableArray array];
    }
    return _storeList;
}

@end
